import os
import requests
from datetime import datetime
from config.settings import TITLE_REGEX


class FileHandler:
    def __init__(self):
        # 初始化缓存列表
        self.write_cache = []
        self.batch_size = 50  # 设置每次写入的条数阈值
        self.file_path = self.get_file_path()

    def get_file_path(self):
        current_date = datetime.now().strftime('%Y-%m-%d')
        project_root = os.getcwd()
        folder_path = os.path.join(project_root, current_date)
        # 如果文件夹不存在则创建
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
        return os.path.join(folder_path, 'other-status.txt')

    def write_to_file(self):
        if not self.write_cache:
            return
        with open(self.file_path, 'a', encoding='utf-8') as file:
            file.writelines(self.write_cache)
        self.write_cache.clear()

    def operation_on_failure(self, url, status_code):
        self.write_cache.append(f"{url}    {status_code}\n")

        # 如果缓存满了，批量写入文件
        if len(self.write_cache) >= self.batch_size:
            self.write_to_file()

    def flush_cache(self):
        #结束时将缓存写入文件
        if self.write_cache:
            self.write_to_file()


class RequestHandler:
    def __init__(self):
        # 初始化缓存列表
        self.write_cache = []
        self.batch_size = 50  # 设置每次写入的条数阈值
        self.file_path = self.get_file_path()

    def get_file_path(self):
        """根据当前日期生成文件路径"""
        current_date = datetime.now().strftime('%Y-%m-%d')
        project_root = os.getcwd()  # 获取项目根路径
        folder_path = os.path.join(project_root, current_date)
        # 如果文件夹不存在则创建
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
        return os.path.join(folder_path, '30x.txt')

    def write_to_file(self):
        """将缓存数据写入文件"""
        if not self.write_cache:
            return
        with open(self.file_path, 'a', encoding='utf-8') as file:
            file.writelines(self.write_cache)
        self.write_cache.clear()

    def operation_on_try(self, url):
        """根据传入的 URL 发起请求，处理返回信息并存入缓存"""
        # 发起 HTTP 请求
        try:
            response = requests.get(url)
            # 获取状态码
            status_code = response.status_code
            # 使用正则表达式提取<title>标签内容（此部分假设你已经有 TITLE_REGEX 定义）
            title_search = TITLE_REGEX.search(response.text)  # 假设已定义 TITLE_REGEX
            title = title_search.group(1) if title_search else "No title"

            # 获取跳转地址（如果是 302）
            redirect_url = response.headers.get('Location', None) if status_code == 302 else None

            # 将信息添加到缓存
            if redirect_url:
                self.write_cache.append(f"{url} {status_code} {title} 302跳转地址--{redirect_url}\n")
            else:
                self.write_cache.append(f"{url} {status_code} {title}\n")

            # 如果缓存满了，批量写入文件
            if len(self.write_cache) >= self.batch_size:
                self.write_to_file()

        except requests.exceptions.RequestException as e:
            print(f"请求过程中出错: {e}")

    def flush_cache(self):
        """确保将缓存中的所有数据写入文件"""
        if self.write_cache:
            self.write_to_file()
